<script setup>
import { ref } from 'vue';
import { useFormOperate } from '@/hooks/pages-repeat';
import { createApi, updataApi, getInfoApi } from '@/api/sys/dept';
import { listApi } from '@/api/sys/dept';

const emits = defineEmits(['modalClose'])
const { 
  dataFormRef,
  modalOpen,
  confirmLoading,
  detailLoading,
  dataForm,
  requestObj,
  submit,
  init
} = useFormOperate()

requestObj.value = {
  createApi,
  updataApi,
  getInfoApi,
  submitCallback: emits
}
dataForm.value = {
  id: undefined,
  name: '',
  pid: undefined,
  parentName: '',
  sort: 0
}
const rules = ref({
  name: [{ required: true, message: '请输入名称!' }],
  pid: [{ required: true, message: '请选择上级部门!' }]
})
const deptList = ref([])

const getDepList = () => {
  listApi().then(({data:res}) => {
    deptList.value = [
      {
        pid: '0',
        id: '0',
        name: '一级菜单',
      },
      ...res.data
    ]
  })
}

getDepList()

defineExpose({
  init
})

</script>

<template>
  <a-modal 
    width="40%"
    v-model:open="modalOpen" 
    :confirm-loading="confirmLoading"
    :title="dataForm.id ? '修改部门' : '新增部门'" 
    okText="确定"
    cancelText="取消"
    :maskClosable="false"
    :bodyStyle="{'padding': '20px'}"
    @cancel="emits('modalClose')"
    @ok="submit"
    >
    <a-spin :spinning="detailLoading">
      <a-form ref="dataFormRef" layout="vertical" :model="dataForm" :rules="rules" name="dataForm" autocomplete="off">
        <a-form-item label="编码" name="name">
          <a-input v-model:value.trim="dataForm.name" placeholder="请输入名称" />
        </a-form-item>

        <a-form-item label="上级菜单" name="pid">
          <a-tree-select
            v-model:value.trim="dataForm.pid"
            show-search
            style="width: 100%"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            placeholder="请选择上级菜单"
            allow-clear
            :tree-data="deptList"
            :field-names="{
              label: 'name',
              value: 'id',
            }"
            tree-node-filter-prop="name"
            @change="(value, label, extra) => dataForm.parentName=label[0]"
          >
          </a-tree-select>
        </a-form-item>

        <a-form-item label="排序">
          <a-input-number style="width: 100%;" v-model:value.trim="dataForm.sort" :min="0" />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<style lang="scss" scoped>

</style>